package cn.schoolwow.util.test.module.replaceFile.ruoyi.flow;

import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import cn.schoolwow.util.domain.query.resource.QueryResource;
import cn.schoolwow.util.domain.query.resource.QueryResourceResponse;
import cn.schoolwow.util.domain.replace.ReplaceFile;
import cn.schoolwow.util.module.query.resource.domain.SingleQueryResourceHandler;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.List;

public class ModifyJavaFileFlow implements BusinessFlow {
    private static String[] prefixPackageNameArray = new String[]{
            "org.dromara","com.ruoyi"
    };
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        replacePackageName(flowContext);
        moveJavaFileDirectory(flowContext);
        deleteEmptyDirectory(flowContext);
    }

    @Override
    public String name() {
        return "修改java文件";
    }

    private void replacePackageName(FlowContext flowContext){
        String directoryPath = flowContext.checkData("directoryPath", String.class);
        String groupIdName = flowContext.checkData("groupIdName",String.class);
        Path basePath = flowContext.checkData("basePath", Path.class);

        QueryResource.newQuery("java文件", directoryPath)
                .fileNameEndWith(".java")
                .singleQueryResourceHandler(new SingleQueryResourceHandler() {
                    @Override
                    public boolean handleQueryResourceResponse(QueryResourceResponse queryResourceResponse) {
                        File file = queryResourceResponse.getAsFile();

                        ReplaceFile replaceFile = ReplaceFile.queryFile(file);
                        for(String prefixPackageName:prefixPackageNameArray){
                            replaceFile.addReplaceString("package "+prefixPackageName, "package "+groupIdName)
                                    .addReplaceString("import "+prefixPackageName, "import "+groupIdName)
                                    .addReplaceString("import static "+prefixPackageName, "import static "+groupIdName)
                                    .addReplaceString("import "+prefixPackageName+".**", "import "+groupIdName+".**")
                                    .addReplaceString(prefixPackageName, groupIdName);
                        }
                        replaceFile.replaceFile();
                        String sourcePath = basePath.relativize(file.toPath()).toString();
                        System.out.println("替换java文件["+sourcePath+"]");
                        return true;
                    }
                })
                .execute()
                .walkResource();

        //排除import com.ca.sms4j.api.dao.SmsDao;
        QueryResource.newQuery("java文件", directoryPath)
                .fileNameEndWith(".java")
                .singleQueryResourceHandler(new SingleQueryResourceHandler() {
                    @Override
                    public boolean handleQueryResourceResponse(QueryResourceResponse queryResourceResponse) {
                        File file = queryResourceResponse.getAsFile();
                        ReplaceFile.queryFile(file)
                                .addReplaceString("import "+groupIdName+".sms4j", "import org.dromara.sms4j")
                                .replaceFile();
                        String sourcePath = basePath.relativize(file.toPath()).toString();
                        System.out.println("替换java文件["+sourcePath+"]");
                        return true;
                    }
                })
                .execute()
                .walkResource();

        QueryResource.newQuery(".imports文件", directoryPath)
                .fileNameEndWith(".imports")
                .singleQueryResourceHandler(new SingleQueryResourceHandler() {
                    @Override
                    public boolean handleQueryResourceResponse(QueryResourceResponse queryResourceResponse) {
                        File file = queryResourceResponse.getAsFile();
                        ReplaceFile replaceFile = ReplaceFile.queryFile(file);
                        for(String prefixPackageName:prefixPackageNameArray){
                            replaceFile.addReplaceString(prefixPackageName+".", groupIdName+".");
                        }
                        replaceFile.replaceFile();
                        String sourcePath = basePath.relativize(file.toPath()).toString();
                        System.out.println("替换imports文件["+sourcePath+"]");
                        return true;
                    }
                })
                .execute()
                .walkResource();

        QueryResource.newQuery("mapper文件", directoryPath)
                .fileNameEndWith("Mapper.xml")
                .singleQueryResourceHandler(new SingleQueryResourceHandler() {
                    @Override
                    public boolean handleQueryResourceResponse(QueryResourceResponse queryResourceResponse) {
                        File file = queryResourceResponse.getAsFile();
                        ReplaceFile replaceFile = ReplaceFile.queryFile(file);
                        for(String prefixPackageName:prefixPackageNameArray){
                            replaceFile.addReplaceString("\""+prefixPackageName+".", "\""+groupIdName+".");
                        }
                        replaceFile.replaceFile();
                        String sourcePath = basePath.relativize(file.toPath()).toString();
                        System.out.println("替换xml文件["+sourcePath+"]");
                        return true;
                    }
                })
                .execute()
                .walkResource();

        QueryResource.newQuery("yml配置文件", directoryPath)
                .fileNameEndWith("application.yml")
                .singleQueryResourceHandler(new SingleQueryResourceHandler() {
                    @Override
                    public boolean handleQueryResourceResponse(QueryResourceResponse queryResourceResponse) {
                        File file = queryResourceResponse.getAsFile();
                        ReplaceFile replaceFile = ReplaceFile.queryFile(file);
                        for(String prefixPackageName:prefixPackageNameArray){
                            replaceFile.addReplaceString(prefixPackageName, groupIdName);
                        }
                        replaceFile.replaceFile();
                        String sourcePath = basePath.relativize(file.toPath()).toString();
                        System.out.println("替换yml文件["+sourcePath+"]");
                        return true;
                    }
                })
                .execute()
                .walkResource();
    }

    private void moveJavaFileDirectory(FlowContext flowContext){
        String directoryPath = flowContext.checkData("directoryPath", String.class);
        Path basePath = flowContext.checkData("basePath", Path.class);

        //修改java文件包为文件夹
        QueryResource.newQuery("java文件", directoryPath)
                .fileNameEndWith(".java")
                .singleQueryResourceHandler(new SingleQueryResourceHandler() {
                    @Override
                    public boolean handleQueryResourceResponse(QueryResourceResponse queryResourceResponse) throws IOException {
                        File file = queryResourceResponse.getAsFile();
                        List<String> lines = FileUtils.readLines(file, StandardCharsets.UTF_8);
                        String firstLine = null;
                        for(int i=0;i<lines.size();i++){
                            if(lines.get(i).startsWith("package ")){
                                firstLine = lines.get(i);
                                break;
                            }
                        }
                        if(null==firstLine){
                            System.out.println("查找java文件package 行失败!文件路径:"+file);
                            return false;
                        }
                        try {
                            if(firstLine.startsWith("/**")){

                            }
                            String packageName = firstLine.substring("package ".length(),firstLine.indexOf(";"));
                            String relativePath = packageName.replace(".","/");

                            File currentFile = file;
                            while(!currentFile.getName().equalsIgnoreCase("java")){
                                currentFile = currentFile.getParentFile();
                            }
                            File dir = new File(currentFile.getAbsolutePath()+"/"+relativePath);
                            dir.mkdirs();

                            File targetFile = new File(dir.getAbsolutePath()+"/"+file.getName());
                            if(targetFile.exists()){
                                return true;
                            }

                            System.out.println("移动文件["+basePath.relativize(file.toPath())+"]到目录["+basePath.relativize(dir.toPath())+"]");
                            FileUtils.moveToDirectory(file, dir, false);
                            return true;
                        }catch (Exception e){
                            System.out.println("解析java文件失败!文件路径:"+file+"\r\n第一行内容:"+firstLine);
                            return false;
                        }
                    }
                })
                .execute()
                .walkResource();
    }

    private void deleteEmptyDirectory(FlowContext flowContext){
        String directoryPath = flowContext.checkData("directoryPath", String.class);
        Path basePath = flowContext.checkData("basePath", Path.class);

        QueryResource.newQuery("java文件", directoryPath)
                .singleQueryResourceHandler(new SingleQueryResourceHandler() {
                    @Override
                    public boolean handleQueryResourceResponse(QueryResourceResponse queryResourceResponse) throws IOException {
                        File file = queryResourceResponse.getAsFile();
                        if(file.getName().endsWith(".iml")&&file.getName().startsWith("ruoyi-")){
                            System.out.println("删除iml文件["+basePath.relativize(file.toPath())+"]");
                            FileUtils.delete(file);
                            return true;
                        }
                        if(!file.isDirectory()){
                            return true;
                        }
                        if(file.listFiles().length==0){
                            System.out.println("删除空目录["+basePath.relativize(file.toPath())+"]");
                            FileUtils.deleteDirectory(file);
                            return true;
                        }
                        return true;
                    }
                })
                .execute()
                .walkResource();
    }
}
